/*
 * Copyright 2000-2006 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.gwt.inspections;

import com.intellij.gwt.GwtConfiguration;
import com.intellij.gwt.module.model.GwtModule;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.util.IncorrectOperationException;
import com.intellij.javaee.model.xml.web.WebApp;
import com.intellij.javaee.model.xml.web.Servlet;
import com.intellij.javaee.model.xml.web.ServletMapping;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * @author nik
 */
public class RemoteServiceUtil {
  @NonNls public static final String REMOTE_SERVICE_INTERFACE_NAME = "com.google.gwt.user.client.rpc.RemoteService";
  @NonNls public static final String ASYNC_CALLBACK_INTERFACE_NAME = "com.google.gwt.user.client.rpc.AsyncCallback";
  @NonNls public static final String IS_SERIALIZABLE_INTERFACE_NAME = "com.google.gwt.user.client.rpc.IsSerializable";
  @NonNls public static final String REMOTE_SERVICE_SERVLET_NAME = "com.google.gwt.user.server.rpc.RemoteServiceServlet";
  @NonNls public static final String ASYNC_SUFFIX = "Async";
  @NonNls public static final String IMPL_SERVICE_SUFFIX = "Impl";

  private RemoteServiceUtil() {
  }

  public static boolean isMethodPresentedInAsync(PsiMethod method, @NotNull PsiClass async) {
    PsiType asyncCallbackType = createAsynchCallbackType(async);
    PsiParameter[] params = method.getParameterList().getParameters();

find:
    for (PsiMethod asyncMethod : async.findMethodsByName(method.getName(), false)) {
      final PsiType returnType = asyncMethod.getReturnType();
      if (returnType == null || !returnType.equals(PsiType.VOID)) continue;

      PsiParameter[] asyncParams = asyncMethod.getParameterList().getParameters();

      if (asyncParams.length != params.length + 1) continue;


      for (int i = 0; i != params.length; ++i) {
        if (!params[i].getType().equals(asyncParams[i].getType())) {
          continue find;
        }
      }


      if (asyncParams[params.length].getType().equals(asyncCallbackType)) {
        return true;
      }
    }
    return false;
  }

  public static boolean isRemoteServiceInterface(final PsiClass aClass) {
    if (!aClass.isInterface() || !GwtConfiguration.getInstance().isValidConfiguration()) return false;

    final PsiClass remoteService = aClass.getManager().findClass(REMOTE_SERVICE_INTERFACE_NAME, aClass.getResolveScope());

    return remoteService != null && aClass.isInheritor(remoteService, true);
  }

  public static boolean isRemoteServiceImplementation(final PsiClass aClass) {
    if (aClass.isInterface() || !GwtConfiguration.getInstance().isValidConfiguration()) return false;

    final PsiClass servlet = aClass.getManager().findClass(REMOTE_SERVICE_SERVLET_NAME, aClass.getResolveScope());
    return servlet != null && aClass.isInheritor(servlet, true);
  }

  public static @Nullable PsiClass findRemoteServiceInterface(PsiClass serviceImpl) {
    final PsiClass[] interfaces = serviceImpl.getInterfaces();
    for (PsiClass anInterface : interfaces) {
      if (isRemoteServiceInterface(anInterface)) {
        return anInterface;
      }
    }
    return null;
  }

  public static @Nullable PsiClass findSynchronousService(final PsiClass asynchInterface) {
    final PsiManager psiManager = asynchInterface.getManager();

    final GlobalSearchScope scope = asynchInterface.getResolveScope();
    final PsiClass remoteService = psiManager.findClass(REMOTE_SERVICE_INTERFACE_NAME, scope);
    if (remoteService == null) {
      return null;
    }

    String name = asynchInterface.getQualifiedName();
    if (name != null && name.endsWith(ASYNC_SUFFIX)) {
      final PsiClass sync = psiManager.findClass(name.substring(0, name.length() - ASYNC_SUFFIX.length()), scope);
      if (sync != null && sync.isInheritor(remoteService, true)) {
        return sync;
      }
    }
    return null;
  }

  public static @Nullable PsiClass findAsynchronousInterface(PsiClass aClass) {
    return aClass.getManager().findClass(aClass.getQualifiedName() + ASYNC_SUFFIX, aClass.getResolveScope());
  }

  public static void copyMethodsToAsync(final PsiClass sync, PsiClass async) throws IncorrectOperationException {
    final PsiType asyncCallbackType = createAsynchCallbackType(sync);
    PsiElementFactory elementFactory = sync.getManager().getElementFactory();

    for (PsiMethod met : async.getMethods()) {
      met.delete();
    }

    for (PsiMethod met : sync.getMethods()) {
      PsiMethod newMet = (PsiMethod)met.copy();
      newMet.getParameterList().add(elementFactory.createParameter("async", asyncCallbackType));
      final PsiReferenceList throwsList = newMet.getThrowsList();
      for (PsiJavaCodeReferenceElement element : throwsList.getReferenceElements()) {
        element.delete();
      }
      final PsiTypeElement returnTypeElement = newMet.getReturnTypeElement();
      assert returnTypeElement != null;
      returnTypeElement.replace(elementFactory.createTypeElement(PsiType.VOID));
      async.add(newMet);
    }
  }

  public static PsiClassType createAsynchCallbackType(PsiClass aClass) {
    final PsiManager psiManager = aClass.getManager();
    return psiManager.getElementFactory().createType(psiManager.findClass(RemoteServiceUtil.ASYNC_CALLBACK_INTERFACE_NAME, aClass.getResolveScope()));
  }

  public static String getServletPath(GwtModule module, String serviceName) {
    return "/" + module.getQualifiedName() + "/" + serviceName;
  }

  public static String getServletName(final GwtModule gwtModule, final String serviceName) {
    return gwtModule.getQualifiedName() + " " + serviceName;
  }

  public static void registerServletForService(final GwtModule gwtModule, final WebApp root, final PsiClass servletImpl,
                                         final String serviceName) {
    final Servlet servlet = root.addServlet();
    servlet.getServletClass().setValue(servletImpl);
    final String servletName = getServletName(gwtModule, serviceName);
    servlet.getServletName().setValue(servletName);

    final ServletMapping mapping = root.addServletMapping();
    mapping.getServletName().setValue(servlet);
    mapping.addUrlPattern().setValue(getServletPath(gwtModule, serviceName));
  }

  public static boolean isServiceRegistered(GwtModule gwtModule, WebApp root, PsiClass servletImpl) {
    final List<Servlet> servlets = root.getServlets();
    final PsiManager psiManager = servletImpl.getManager();
    for (Servlet servlet : servlets) {
      if (psiManager.areElementsEquivalent(servletImpl, servlet.getServletClass().getValue())) {
        return true;
      }
    }
    return false;
  }
}
